#pragma once

#include <iostream>
#include <vector>

namespace solution_082
{

struct ListNode
{
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) { }
    ListNode(int x) : val(x), next(nullptr) { }
    ListNode(int x, ListNode *next) : val(x), next(next) { }
};

class Solution
{
public:
    ListNode* deleteDuplicates(ListNode* head)
    {
        if (head == nullptr)
            return head;

        auto root = ListNode(head->val - 1, head);
        auto prev = &root;
        auto node = prev->next;

        while (node) {
            if (node->val != root.val) {
                root.val = node->val;
                node = node->next;
            }
            if (node && node->val == root.val) {
                do {
                    prev->next = node->next;
                    node = node->next;
                } while (node && node->val == root.val);
            } else {
                prev = prev->next;
            }
        }

        return root.next;
    }
};

}  /* namespace solution_082 */
